package com.lk.controller;

import com.lk.beans.User;
import com.lk.service.UserService;
import com.lk.vo.ResultInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    UserService userService=new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String actionName=req.getParameter("actionName");
        if("login".equals(actionName)){

            userLogin(req,resp);
        }
    }

    private void userLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName= req.getParameter("userName");
        String userPwd= req.getParameter("userPwd");

        ResultInfo<User> resultInfo= userService.userLogin(userName,userPwd);
        if(resultInfo.getCode()==1){
            //成功将信息存入session
            HttpSession session = req.getSession();
            session.setAttribute("user",resultInfo.getResult());
            String rem=req.getParameter("rem");
            //判断是否记住密码
//            if(rem==null) {
//                Cookie cookie=new Cookie("user",null);
//                cookie.setMaxAge(0);//三天
//                resp.addCookie(cookie);
//            }
//            else
            if("1".equals(rem)){
                Cookie cookie=new Cookie("user",userName+"-"+userPwd);
                cookie.setMaxAge(3*24*60*60);//三天
                resp.addCookie(cookie);
            }else {
                Cookie cookie=new Cookie("user",null);
                cookie.setMaxAge(0);
                resp.addCookie(cookie);
            }
            resp.sendRedirect("welcome.jsp");
        }else {
            req.setAttribute("resultInfo",resultInfo);
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
